﻿#include "sysgnfindpathmodel.h"
#include "server_global.h"
#include "sysserverclientsocket.h"
#include "cgproto.pb.h"

SysGnFindPathModel::SysGnFindPathModel()
{

}

void SysGnFindPathModel::f_pushPaths(CnsComponentPtr com, qttp::HttpData& httpData)
{
    const QJsonObject& json = httpData.getRequest().getJson();
    const QString& filter = json["filter"].toString();
    com->setPropertyInNs(filter, "filter");
    QJsonObject& resp = httpData.getResponse().getJson();
    resp["response"] = QSTR("save ok!");
}

void SysGnFindPathModel::delThread(CnsComponentPtr com, DbQueryBaseThread* thread)
{
    DBQUERYBASETHREADPTRSET threads = com->property("threads").value<DBQUERYBASETHREADPTRSET>();
    threads.remove(thread);
    thread->release();
}

void SysGnFindPathModel::f_pushFilePaths(CnsComponentPtr com, GnFindPathThreadPtr thread)
{
    cgproto::FilePathsNotice fpNotice;
    PathFilesInfoMap &map = thread->getFilterFilePaths();
    {
        QReadLocker(&thread->getReadWriteLock());
        for(PathFilesInfoMap::iterator it = map.begin(); it != map.end(); it++)
        {
            if(it.value()._status & FilesInfoStatus::FINISH_PATH){
                cgproto::FilePathsNotice::PathFiles *pfs = fpNotice.add_filepaths();
                pfs->set_path(it.key().toLatin1());
                pfs->set_files(it.value()._files.toLatin1());
            }
        }
    }

    for(QSet<ServerClientSocketProc*>::const_iterator it = thread->getSocket().begin(); it != thread->getSocket().end(); it ++)
    {
        (*it)->msgSend(ProtoType::FILE_PATHS_NOTICE, fpNotice);
    }
}


GnFindPathDBThread* SysGnFindPathModel::newQueryThread(CnsComponentPtr com, QVariantHash& sv)
{
    static uint64_t threads = 1;
    GnFindPathDBThreadPtr dbpt = FRAMEWORK->newComponent(QString("GnFindPathThread%1").arg(threads++), "/server/.//gnFindPathDBThread").staticCast<GnFindPathDBThread>();
    GnFindPathThreadPtr pt = dbpt->property("gnFindPathThread").value<GnFindPathThreadPtr>();
    ServerClientSocketProcPtr socket = sv["ServerClientSocketProc"].value<ServerClientSocketProcPtr>();
    if(pt->getStart()){
        pt->pushSocket(socket.data());
    } else {
        pt->pushSocket(socket.data());
        dbpt->execInNs("initDbQueryThread", "",
                   Q_ARG(QVariantHash&, sv), Q_ARG(QScopedPointer<QThread>&, dbpt->getWorkThread()));
        connect(dbpt.data(), &GnFindPathDBThread::dbQueryThreadFinished, this, [com, this](CnsComponentPtr tcom){
            emitPushFilePaths(com, tcom);
        });
    }

    return dbpt.data();
}

void SysGnFindPathModel::f_emitPushFilePaths(CnsComponentPtr com, const QVariantHash& props)
{
    emitPushFilePaths(com, props["thread_com"].value<CnsComponentPtr>());
}

void SysGnFindPathModel::emitPushFilePaths(CnsComponentPtr com, CnsComponentPtr thread_com)
{
    GnFindPathDBThreadPtr threadDB = thread_com.staticCast<GnFindPathDBThread>();
    GnFindPathThreadPtr thread = threadDB->property("gnFindPathThread").value<GnFindPathThreadPtr>();
    if(threadDB->isForceStop())return;
    if(threadDB->getProps()["finish"] == true)
    {
        delThread(com, threadDB.data());
        int ret = FRAMEWORK->removeRefObj(threadDB->getObjFullPath(), true);
        assert(ret);
    }

    com->exec("pushFilePaths", Q_ARG(GnFindPathThreadPtr, thread));
}

void SysGnFindPathModel::f_loginSuccess(CnsComponentPtr com, ServerClientSocketProcPtr serverClientSocketProcPtr)
{
    QString filter = com->propertyInNs("filter").toString();
    QVariantHash sv;
    sv["filter"] = filter;
    sv["ServerClientSocketProc"] = QVariant::fromValue(serverClientSocketProcPtr);
    const QString& dir = com->property("ObserveFilesDirectory").toString();
    sv["filesDirectory"] = dir;
    const QString& fileName = com->property("fileName").toString();
    sv["fileName"] = fileName;
    QSSHASH hash;
    QStringList l = dir.split('/', QString::SkipEmptyParts);
    if(l.size())
    {
        l[0].replace(':', "");
    }
    hash["@Table"] = filter.replace('.', "") +'_' + l.join('_');
    sv["patterns"] = QVariant::fromValue(hash);
    newQueryThread(com, sv);
}
